<template>

  <div class="box">
    <MyPlayer :video-id="data.videoId" :url="data.videoUrl"></MyPlayer>
<!--    <TestPlayer></TestPlayer>-->
    <el-card>
      <div class="support-video">
        <div class="like">
          <img src="/icon/no-like-icon.webp" v-if="!currentActionStatus.hasLike" @click="doLike(data.videoId,data.videoOwnerId)" alt="" width="20">
          <img src="/icon/has-like-icon.webp" v-else @click="doLike(data.videoId,data.videoOwnerId)" alt="" width="20">
          {{ data.videoLikeCount }}
        </div>
        <div class="save">
          <el-icon @click="save(data.videoId)" v-if="!currentActionStatus.hasSave"><Star /></el-icon>&nbsp;&nbsp;
          <img src="/icon/has-save-icon.webp" @click="save(data.videoId)" v-else alt="" width="20">
          {{ data.videoSaveCount }}
        </div>
        <div class="share">
          <el-icon @click="share()"><Share /></el-icon>&nbsp;&nbsp;&nbsp;
          {{data.videoForwardCount}}
        </div>
      </div>
    </el-card>
    <div class="video-profile">
      <div class="introduction">{{ data.videoIntroduction }}</div>
      <div class="tag">
        <el-tag type="info" style="margin: 0 10px;" v-for="item in data.videoTag">{{ item }}</el-tag>
      </div>
    </div>
    <!-- 收藏对话框 -->
    <el-dialog v-model="saveDialogVisible" title="添加到收藏夹" width="450" center>
      <el-table
          ref="tableRef"
          :data="saveFolderList"
          row-key="folderId"
          style="width: 100%"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" reserve-selection width="55" />
        <el-table-column width="120">
          <template #default="scope">
            {{ scope.row.saveName }}
          </template>
        </el-table-column>
        <el-table-column property="name" width="220">
          <template #default="scope">
            <div style="width: 200px;text-align: right">{{ scope.row.recordCount }}</div>
          </template>
        </el-table-column>
      </el-table>
      <div class="insert-save-folder" @click="isInput = true" v-if="!isInput">
        <el-icon style="font-size: 20px;font-weight: bold;"><Plus /></el-icon>
        &nbsp;
        新建收藏夹
      </div>
      <div class="insert-save-folder-input" v-else>
        <el-input v-model="folderForm.saveName"
                  @blur="handleBlur"
                  placeholder="请输入收藏夹名称"></el-input>
        <el-button type="primary" @click="mkdir()">新建</el-button>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button :type="curSaveStatus?'primary':'default'" @click="doSave">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
      <!-- 分享对话框 -->
    <el-dialog style="padding: 25px;border-radius: 10px" v-model="dialogVisible" title="分享到动态" width="550" draggable>
      <el-input
          v-model="forwardForm.forwardDesc"
          style="width: 500px"
          :rows="3"
          type="textarea"
          placeholder="来说说分享的理由？| · w · ）"
      />
      <div class="share-box">
        <div class="share-header">
          <el-avatar :src="data.userAvatar" :size="30"></el-avatar>&nbsp;
          <span class="nickname">{{data.videoOwnerNickname}}</span>&nbsp;
          的投稿视频
        </div>
        <div class="share-content">
          <div class="content-left">
            <el-image :src="data.videoCover" style="width: 230px;height: 130px;overflow: hidden;border-radius: 5px;" fit="cover"></el-image>
          </div>
          <div class="content-right">
            <div>{{data.videoTitle}}</div>
            <div>{{data.videoIntroduction}}</div>
            <div class="bottom-info">
              <el-icon><VideoPlay /></el-icon> &nbsp;{{data.playCount}} &nbsp;&nbsp;
              <el-icon><ChatLineSquare /></el-icon> &nbsp;{{data.videoBarrageCount}}
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="doShare()">
            发布
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import {nextTick, onMounted, reactive, ref, watch} from "vue";
import MyPlayer from "@/components/MyPlayer.vue";
import TestPlayer from "@/components/player/TestPlayer.vue";
import {
  forwardVideo,
  getLikeSaveStatusInVideo,
  getSaveFolder,
  getSaveFolderIdByVId,
  insertSaveFolder,
  likeVideo,
  saveVideo
} from "@/api/api.js";
import {useUserStore} from "@/stores/userInfoStore.js";
import {ElMessage} from "element-plus";
import emitter from "@/utils/emitter.js";

const prop = defineProps(["data"])

/* 点赞相关*/
const form = {
  supporterId: 0,
  likeContentId:0,
  contentOwnerId:0
}
// 点赞
const doLike = async (videoId,ownerId) => {
  form.supporterId = useUserStore().userInfo.userId
  form.likeContentId = videoId
  form.contentOwnerId = ownerId
  if(form.supporterId === form.contentOwnerId){
    ElMessage.error("不能给自己点赞")
    return;
  }
  const res = await likeVideo(form)
  console.log(res)
  if(res.code === 200){
    console.log(res.msg)
    console.log(res.data)
    if(res.msg.includes("取消")){
      ElMessage.success(res.msg);
      prop.data.videoLikeCount--
      await getActionStatus()
      return;
    }
    ElMessage.success("点赞成功！")
    prop.data.videoLikeCount++
    await getActionStatus()
  }
}

const currentActionStatus = ref({
  hasLike:false,
  hasSave:false
})
onMounted(async ()=>{
  if(localStorage.getItem("userId")){
   await getActionStatus()
  }
})
const getActionStatus = async () => {
  const res = await getLikeSaveStatusInVideo(prop.data.videoId)
  console.log(res)
  currentActionStatus.value = res.data
}
/* 点赞相关结束 */

/* 收藏相关 */
const saveForm = reactive({
  videoId: 0,
  folderIds: []
})
const saveList = ref([])
const curSaveStatus = ref(false)

const save = async (videoId) => {

  if(!useUserStore().userInfo.userId){
    emitter.emit("showLogin",true)
    emitter.on("userInfo",async (val)=>{
      await initSaveFolder();
      saveDialogVisible.value = true;
      setInitialSelection()
      saveForm.videoId = videoId;
    })
    return ;
  }
  saveDialogVisible.value = true;
  await initSaveFolder();
  setInitialSelection()
  saveForm.videoId = videoId;
}

const doSave = async (id) => {
  saveForm.videoId = prop.data.videoId
  saveForm.folderIds = []
  saveList.value.forEach(ele=>{
    saveForm.folderIds.push(ele.folderId)
  })
  if(saveForm.folderIds.length === 0){
    folderStatus.value++
    decrementStatus.value++
  }else {
    incrementStatus.value++
  }
  if(folderStatus.value === 2){
    console.log("未选中收藏夹")
    saveDialogVisible.value = false
    return
  }

  const res = await saveVideo(saveForm)
  console.log("保存视频成功！")
  console.log(res)
  saveDialogVisible.value = false
  if(res.code === 200){
    // if(folderStatus.value == 2){
    //   prop.data.videoSaveCount++
    // }else {
    //   prop.data.videoSaveCount--
    // }
    if(decrementStatus.value === 2){
      prop.data.videoSaveCount --
    }
    if(incrementStatus.value === 2){
      prop.data.videoSaveCount ++
    }
    ElMessage.success("操作成功！")
    await getActionStatus()
  }
}

// 收藏夹列表
const saveDialogVisible = ref(false)
const saveFolderList = ref([
  {
    folderId:0,
    saveName:'',
    recordCount:0,
    row:false
  }
])


const getRowKey = (val) => {
  console.log(val)
  return "id123"
}



let userId = localStorage.getItem("userId")
let videoId = prop.data.videoId
// onMounted(async ()=>{
//   // 根据视频id和用户id查询点赞，收藏，分享等状态
//   const res = await getLikeStatus();
// })
/* 状态相关 */

// 新增收藏夹
const folderForm = reactive({
  saveName:'',
})
const handleBlur = () => {
  setTimeout(() => {
    console.log("失去焦点事件触发...")
    isInput.value = false
  }, 100)
}
const isInput = ref(false)
const mkdir = async () => {
  const res = await insertSaveFolder(folderForm)
  console.log("创建收藏夹后的消息")
  console.log(res)
  if(res.code === 200){
    ElMessage.success("创建成功！")
    const res1 = await getSaveFolder(useUserStore().userInfo.userId);
    console.log(res1)
    saveFolderList.value = res1.data.records
  }else{
    ElMessage.error("收藏失败")
  }
}

// 收藏夹选中
const tableRef = ref()
const multipleSelection = ref([])

const folderStatus = ref(0) // 状态：在没数据与提交时没数据时会停止请求
const incrementStatus = ref(0) // 状态：在没数据与提交时有数据时会saveCount加一
const decrementStatus = ref(0) // 状态：在没数据与提交时有数据时会saveCount加一
const initSaveFolder = async () => {
  folderStatus.value = 0
  incrementStatus.value = 0
  decrementStatus.value = 0
  const userId = useUserStore().userInfo.userId
  // 获取收藏夹列表
  const res = await getSaveFolder(userId);
  // 获取这个视频被那些收藏夹收藏了
  const res1 = await getSaveFolderIdByVId(userId,prop.data.videoId)
  if(res1.data.length !== 0){
    decrementStatus.value++
    res.data.records.forEach(ele=>{
      if(res1.data.some(item=>ele.folderId === item)){
        ele.row = true
      }else{
        ele.row = false
      }
    })
  }else {
    folderStatus.value ++ // 设置信号
    incrementStatus.value ++ // 设置信号
  }
  saveFolderList.value = res.data.records
}

const setInitialSelection = () => {
  nextTick(() => {
    if (!tableRef.value) return
    // 清除所有选中
    tableRef.value.clearSelection()
    // 遍历数据设置选中状态
    saveFolderList.value.forEach(row => {
      if (row.row) {
        console.log(row)
        tableRef.value.toggleRowSelection(row, true)
      }
    })
  })
}

const handleSelectionChange = (val) => {
  saveList.value = val
  if(saveList.value.length !== 0){
    curSaveStatus.value = true
  }else {
    curSaveStatus.value = false
  }
  multipleSelection.value = val
}
/* 收藏相关结束 */

/* 分享相关 */
const forwardForm = reactive({
  forwardContentId:0,
  forwardDesc:''
})
const dialogVisible = ref(false)
const share = () => {
  dialogVisible.value = true
}
const doShare = async () => {
  try {
    dialogVisible.value = false
    forwardForm.forwardContentId = prop.data.videoId
    await forwardVideo(forwardForm)
    ElMessage.success("分享成功")
  }catch (e) {
    ElMessage.error("分享失败"+e)
  }
}
/* 分享相关结束 */
</script>
<style lang="scss" scoped>

.box{
  position: relative;
  width: 800px;
  .el-card__body{
    --el-card-padding:0 0;
  }
  .danmuItem{
    position: absolute;
    right: 0;
    top: 100px;
  }
  .support-video{
    height: 30px;
    display: flex;
    color: gray;
    .like,.save,.share{
      width: 100px;
      height: 30px;
      line-height: 30px;
      cursor: pointer;
    }
  }
  .video-profile{
    box-sizing: border-box;
    height: 120px;
    padding: 10px 20px;
    //background-color: #ffb6b6;
    .introduction{
      //background-color: #a4ff76;
      min-height: 60px;
      line-height: 30px;
    }
    .tag{
      box-sizing: border-box;
      padding: 10px;
    }
  }
  .share-box{
    width: 500px;
    height: 200px;
    background-color: #e7e7e7;
    box-sizing: border-box;
    padding: 10px;
    .share-header{
      .nickname{
        font-size: 14px;
        color:black;
      }
      display: flex;align-items: center;
      //box-sizing: border-box;
      //padding: 5px;
      height: 40px;
      font-size: 12px;
      color: gray;
    }
    .share-content{
      
      display: flex;color: black;
      .content-right{
        background-color: #f5f5f5;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        box-sizing: border-box;
        padding: 10px 20px;
        .bottom-info{
          display: flex;
          align-items: center;
          font-size: 13px;
          color: gray;
        }
      }
    }
  }
}

.insert-save-folder{
  margin-left: 12px;
  width: 376px;
  height: 35px;
  padding-left:15px;
  border-radius: 5px;
  border: 2px solid #c2c2c2;
  //background-color: red;
  color:var(--gray-font-color--);
  font-size:13px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
}
.insert-save-folder-input{
  margin-left: 12px;
  width: 376px;
  height: 35px;
  display: flex;
  //deep(.el-input){
  //  //--el-input-border:2px solid red;
  //  border:2px solid red;
  //}
  .el-input{
    border:2px solid #c2c2c2;
    border-radius: 5px;
    //outline: 2px;
  }
  .is-focus{
    border-radius: 50%;
  }
}
.insert-save-folder:hover{
  border-color: var(--subject-color--);
}
:deep(.el-table__header-wrapper){
  display: none;
}

</style>